<?php

namespace App\Http\Service;

use App\Libs\HttpCurlLibrary;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use App\Models\UserFollows;
use App\Http\Service\UserService;
use App\Models\Comment;
use Illuminate\Support\Facades\DB;
use App\Models\Doubanpost;
use App\Models\Baoliaopost;


//互动消息
class MsgService extends BaseService
{
   
    public function __construct(UserFollows $userFollows,UserService $userService,Comment $comment,Doubanpost $doubanpost,Baoliaopost $baoliaopost)
    {
        parent::__construct();
        $this->userFollows=$userFollows;
        $this->userService=$userService;
        $this->comment=$comment;
        $this->doubanpost=$doubanpost;
        $this->baoliaopost=$baoliaopost;
    }
    #关注列表
    public function dataList()
    {
        $where[]=['status','=','1'];
        $fileds=['follower_id','following_id'];
        $list=$this->userFollows    
            ->where($where)
            ->select($fileds)
            ->get()
            ->toArray();
        $result=[];
        foreach($list as $k=>$v){
            $key="{$v['follower_id']}_{$v['following_id']}";
            $result[$key]=$v;
        }
        return $result;
    }
    # 判断是否相互关注
    public function is_eachfocus($datalist,$data)
    {
        $follower_id=$data['follower_id'];
        $following_id=$data['following_id'];
        $key="{$following_id}_{$follower_id}";
        if(isset($datalist[$key])){
            return true;
        }else{
            return false;
        }

    }

    //互相关注列表
    public  function eachfocusList($request,$data=[])
    {
        $page = intval($request->json('page')) ?$request->json('page') :$this->cpage;
        $limit = intval($request->json('limit')) ?$request->json('limit') :$this->climit;
        $offset = ($page-1)*$limit;
        $where=[];
        $follower_id=$data['people_id'];
        $where[]=['follower_id','=',$follower_id];
        $where[]=['status','=','1'];
        $list=$this->userFollows    
            ->where($where)
            ->offset($offset)
            ->limit($limit)
            ->select()->get()->toArray();
        $datalist =$this->dataList();
        //dd($datalist);
        $keyword=$data['keyword'];
        $result=[];
        # 组合数据
        foreach ($list as $k => $v) {
           $rs=$this->is_eachfocus($datalist,$v);
           if($rs){
                #被关注者用户信息
                $people_id=$v['following_id'];
                $userData= $this->userService->update_user($people_id);
                $v['nickname']=$userData['nickname'];
                $v['avatar']=$userData['avatar'];

                $search=containsKeyword($v['nickname'], $keyword);
                //dd($search);
                if($search){
                    # 3= 互相关注
                    $v['tag_status']='3';
                    $v['tag_msg']='互相关注';
                    $result[]=$v;
                }else{
                    # 3= 互相关注
                    $v['tag_status']='3';
                    $v['tag_msg']='互相关注';
                    $result[]=$v;
                }
                
           }
           

        }
        //dd($result);
        return ($result);

    }

    //用户关注其他用户的信息
    public function userToOther($request,$data=[])
    {
        $page = intval($request->json('page')) ?$request->json('page') :$this->cpage;
        $limit = intval($request->json('limit')) ?$request->json('limit') :$this->climit;
        $offset = ($page-1)*$limit;
        $where=[];
        $follower_id=$data['people_id'];
        $where[]=['follower_id','=',$follower_id];
        $where[]=['status','=','1'];
        $list=$this->userFollows    
            ->where($where)
            ->offset($offset)
            ->limit($limit)
            ->select()->get()->toArray();

        $keyword=$data['keyword'];
        $result=[];
        # 组合数据
        foreach ($list as $k => $v) {
            #被关注者用户信息
            $people_id=$v['following_id'];
            $userData= $this->userService->update_user($people_id);
            $v['nickname']=$userData['nickname'];
            $v['avatar']=$userData['avatar'];

            $search=containsKeyword($v['nickname'], $keyword);
            //dd($search);
            if($search){
                # 2= 已关注
                $v['tag_status']='2';
                $v['tag_msg']='已关注';
                $result[]=$v;
            }else{
                # 2= 已关注
                $v['tag_status']='2';
                $v['tag_msg']='已关注';
                $result[]=$v;
            }
                
        }
        //dd($result);
        return ($result);
   }
    //统计我的粉丝-数量
    public function fansNum($following_id)
    {
        $where[]=['following_id','=',$following_id];
        $where[]=['status','=','1'];
        $count=$this->userFollows    
            ->where($where)
            ->count();
        return $count;
    }
    public function fansNumNo($datalist,$following_id)
    {
        $data=[];
        foreach($datalist as $k=>$v)
        {
            if($v['following_id']==$following_id){
                $data[]=$v['follower_id'];
            }
            
        }
        $count=count($data);
        return $count;
    }
    //我的粉丝
    public function myFans($request,$data=[]){
        $page = intval($request->json('page')) ?$request->json('page') :$this->cpage;
        $limit = intval($request->json('limit')) ?$request->json('limit') :$this->climit;
        $offset = ($page-1)*$limit;
        $where=[];
        $following_id=$data['people_id'];
        #统计用户粉丝数量
        $fansnum=$this->fansNum($following_id);
        //dd($fansnum);
        //dd($following_id);
        $where[]=['following_id','=',$following_id];
        $where[]=['status','=','1'];
        $list=$this->userFollows    
            ->where($where)
            ->offset($offset)
            ->limit($limit)
            ->select()->get()->toArray();
        $datalist =$this->dataList();    
        //dd($list);
        $keyword=$data['keyword'];
        $result=[];
        # 组合数据
        foreach ($list as $k => $v) {
            $rs=$this->is_eachfocus($datalist,$v);
            #被关注者用户信息
            $people_id=$v['follower_id'];
            #粉丝数量
            $v['fansnum']=$this->fansNumNo($datalist,$people_id);
           
            $userData= $this->userService->update_user($people_id);
            $v['nickname']=$userData['nickname'];
            $v['avatar']=$userData['avatar'];

            $search=containsKeyword($v['nickname'], $keyword);

            if($rs){
               
                //dd($search);
                if($search){
                    # 3= 互相关注
                    $v['tag_status']='3';
                    $v['tag_msg']='互相关注';
                    $result[]=$v;
                }else{
                    # 3= 互相关注
                    $v['tag_status']='3';
                    $v['tag_msg']='互相关注';
                    $result[]=$v;
                }
                
           }else{

                if($search){
                    # 2= 已关注
                    $v['tag_status']='2';
                    $v['tag_msg']='已关注';
                    $result[]=$v;
                }else{
                    # 2= 已关注
                    $v['tag_status']='2';
                    $v['tag_msg']='已关注';
                    $result[]=$v;
                }
            }        
        }
        $data_result=[];
        $data_result=[
            'fansnum'=>$fansnum,
            'data'=>$result,
        ];
        //dd($result);
        return ($data_result);

   }
   //谁关注了我
   public function whoTo($request,$data=[])
   {
        $where=[
            'following_id'=>$data['people_id']
        ];
        $list=$this->userFollows    
            ->where($where)
            ->select()->get()->toArray();

        foreach($list as $k=>&$v){
            $people_id=$v['follower_id'];
            $userinfo=$this->userService->update_user($people_id);
            $v['nickname']=$userinfo['nickname'];
            $v['avatar']=$userinfo['avatar'];
            $v['msg']="{$v['nickname']}关注了你";

        }
        return  $list;

   }

   //谁评论了我
    public function whoToComment($request,$data=[])
   {
        $sql="
            SELECT 
                mc.id,
                mc.people_id AS people_id,
                mc.parent_id AS parent_id,
                mc.content AS content,
                mc.create_time AS create_time
            FROM module_comment mc
            WHERE mc.commented_people_id = '{$data['people_id']}'
                AND mc.parent_id IS NOT NULL
                AND mc.status = 1
                AND (mc.is_blocked = 2 OR mc.is_blocked IS NULL)
            ORDER BY mc.create_time DESC";
        //die($sql);
        $list=DB::select($sql);
        $list = array_map('get_object_vars', $list);
        foreach ($list as $k => &$v) {
            $people_id=$v['parent_id'];
            $userinfo=$this->userService->update_user($people_id);
            $v['nickname']=$userinfo['nickname'];
            $v['avatar']=$userinfo['avatar'];
            $v['msg']="{$v['nickname']}评论了你";
        }

       // dd($list);
        return  $list;

   }

   //谁赞了我
   public function whoToLike($request,$data=[])
   {
        $sql="
            SELECT 
                mcl.user_id AS user_id,
                mcl.create_time AS create_time,
                mc.id AS id,
                mc.content AS content
            FROM module_comment_vote mcl
            JOIN module_comment mc ON mcl.comment_id = mc.id
            WHERE mc.people_id = '{$data['people_id']}'  
                AND mc.status = 1  and mcl.vote_type=1
            ORDER BY mcl.create_time DESC";
        //die($sql);
        $list=DB::select($sql); 
        $list = array_map('get_object_vars', $list);
        foreach ($list as $k => &$v) {
            $people_id=$v['user_id'];//点赞用户id
            $userinfo=$this->userService->update_user($people_id);
            $v['nickname']=$userinfo['nickname'];
            $v['avatar']=$userinfo['avatar'];
            $v['msg']="{$v['nickname']}赞了你";
        }
      
        return  $list;
   }


   //谁收藏了我
   public function whoToCollect($request,$data=[])
   {
        //爆料
        $sql="
             SELECT `people_id`,`create_time` FROM `module_baoliao_collect`  where unique_id in (    SELECT `unique_id` FROM `module_baoliao_post`  where user_id='{$data['people_id']}')";
        $list=DB::select($sql); 
        $baoliaolist = array_map('get_object_vars', $list);
        foreach ($baoliaolist as $k => &$v) {
            $people_id=$v['people_id'];//点赞用户id
            $userinfo=$this->userService->update_user($people_id);
            $v['nickname']=$userinfo['nickname'];
            $v['avatar']=$userinfo['avatar'];
            $v['msg']="{$v['nickname']}收藏了你";
        }
      
       // dd($baoliaolist);

        //豆瓣
        $sql="
             SELECT `people_id`,`create_time` FROM `module_douban_collect`  where unique_id in (    SELECT `unique_id` FROM `module_douban_post`  where user_id='{$data['people_id']}')";
        $list=DB::select($sql); 
        $doubanlist = array_map('get_object_vars', $list);
        foreach ($doubanlist as $k => &$v) {
            $people_id=$v['people_id'];//点赞用户id
            $userinfo=$this->userService->update_user($people_id);
            $v['nickname']=$userinfo['nickname'];
            $v['avatar']=$userinfo['avatar'];
            $v['msg']="{$v['nickname']}收藏了你";
        }
        //dd($doubanlist);
        $result=[];
        $result=array_merge($baoliaolist,$doubanlist);
        $result=array_values($result);
        return $result;
   }

   //互动消息：谁关注了我，谁评论了我，谁赞和收藏了我（对方的头像昵称，时间）

   public function allMsg($request,$data=[])
   {
        $page = !empty($data['page']) && intval($data['page']) ?$data['page'] :$this->cpage;
        $limit = !empty($data['limit']) && intval($data['limit']) ?$data['limit'] :$this->climit;
        //dd($data['limit']);
        $offset = ($page-1)*$limit;
        $hdata=[
            'people_id'=>$data['people_id'],
        ];
        $whoTo=$this->whoTo($request,$hdata);

        $whoToComment=$this->whoToComment($request,$hdata);
        $whoToLike=$this->whoToLike($request,$hdata);
        $whoToCollect=$this->whoToCollect($request,$hdata);

        $sortedBy=array_merge($whoTo,$whoToComment,$whoToLike,$whoToCollect);
        $sortedBy=array_values($sortedBy);
        $list= array_slice($sortedBy, $offset, $limit);
        $count = count($sortedBy);

        $result = [
            'page'=> $page,
            'limit'=> $limit,
            'total_page'=> ceil($count/$limit),
            'count'=>$count,
            'data'=> $list
        ];
        return $result; 
   }
   //发布帖子的数量
   public function tieziNum($request,$data=[])
   {
        $where1=[
            'user_id'=>$data['people_id'],
            'channel'=>'app'
        ];
        $fileds=['like_count','collect_count'];
        $doubanNum=0;
        $doubanlike_count=0;
        $doubancollect_count=0;
        $doubanList=$this->doubanpost->where($where1)->select($fileds)->get()->toArray();
        //dd($doubanList);
        foreach($doubanList as $k=>$v){
            $doubanNum=$doubanNum+1;
            $doubanlike_count += $v['like_count'];  // 累加 like_count 的值
            $doubancollect_count += $v['collect_count'];

        }

        //dd($doubanNum);

        $where2=[
            'user_id'=>$data['people_id'],
            'type'=>'2'
        ];
        $baoliaoNum=0;
        $baoliaolike_count=0;
        $baoliaocollect_count=0;
        $baoliaoList=$this->baoliaopost->where($where2)->select($fileds)->get()->toArray();

        foreach($baoliaoList as $k=>$v){
            $baoliaoNum=$baoliaoNum+1;
            $baoliaolike_count += $v['like_count'];  // 累加 like_count 的值
            $baoliaocollect_count += $v['collect_count'];

        }

        $result=[];
        
        $result=[
            'like_count'=>$doubanlike_count+$baoliaolike_count,
            'tiezi_num'=>$doubanNum+$baoliaoNum,
            'collect_num'=>$doubancollect_count+$baoliaocollect_count

        ];

        return $result;
   }

   

   

   //个人中心展示：发布帖子数量，获得赞的数量，获得收藏的数量

   public function  centerNum($request,$data=[])
   {
        $result=$this->tieziNum($request,$data);

        return $result;
   }


}
    


